package com.scrm.server.wx.cp.service.impl;

import com.scrm.common.dto.BatchDTO;
import com.scrm.common.util.ListUtils;
import com.scrm.server.wx.cp.dto.BrGroupSopRuleSaveOrUpdateDTO;
import com.scrm.server.wx.cp.entity.BrGroupSopDetail;
import com.scrm.server.wx.cp.entity.BrTodo;
import com.scrm.server.wx.cp.service.IBrGroupSopDetailService;
import com.scrm.server.wx.cp.service.IBrTodoService;
import com.scrm.server.wx.cp.service.IXxlJobService;
import lombok.extern.slf4j.Slf4j;
import com.scrm.server.wx.cp.entity.BrGroupSopRule;
import com.scrm.server.wx.cp.mapper.BrGroupSopRuleMapper;
import com.scrm.server.wx.cp.service.IBrGroupSopRuleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.scrm.server.wx.cp.dto.BrGroupSopRuleQueryDTO;
import com.scrm.server.wx.cp.vo.BrGroupSopRuleVO;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import com.scrm.common.util.UUID;
import com.scrm.common.exception.BaseException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import java.util.stream.Collectors;

/**
 * 群sop规则 服务实现类
 * @author ouyang
 * @since 2022-04-17
 */
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class BrGroupSopRuleServiceImpl extends ServiceImpl<BrGroupSopRuleMapper, BrGroupSopRule> implements IBrGroupSopRuleService {

    @Autowired
    private IBrGroupSopDetailService detailService;

    @Autowired
    private IXxlJobService xxlJobService;

    @Autowired
    private IBrTodoService todoService;

    @Override
    public List<BrGroupSopRuleVO> queryList(BrGroupSopRuleQueryDTO dto){
        LambdaQueryWrapper<BrGroupSopRule> wrapper = new QueryWrapper<BrGroupSopRule>()
        .lambda().eq(BrGroupSopRule::getExtCorpId, dto.getExtCorpId())
                .eq(BrGroupSopRule::getSopId,dto.getSopId())
                .orderByAsc(BrGroupSopRule::getCreatedAt);
        return Optional.ofNullable(list(wrapper)).orElse(new ArrayList<>()).stream().map(this::translation).collect(Collectors.toList());
    }


    @Override
    public BrGroupSopRuleVO findById(String id){
        return translation(checkExists(id));
    }


    @Override
    public BrGroupSopRule save(BrGroupSopRuleSaveOrUpdateDTO dto){

        //封装数据
        BrGroupSopRule brGroupSopRule = new BrGroupSopRule();
        BeanUtils.copyProperties(dto,brGroupSopRule);
        brGroupSopRule.setId(UUID.get32UUID())
                .setCreatedAt(new Date());

        //入库
        save(brGroupSopRule);

        return brGroupSopRule;
    }


    @Override
    public BrGroupSopRule update(BrGroupSopRuleSaveOrUpdateDTO dto){

        //校验参数
        BrGroupSopRule old = checkExists(dto.getId());
        //封装数据
        BeanUtils.copyProperties(dto, old,"creator");
        old.setUpdatedAt(new Date());
        //入库
        updateById(old);
        return old;

    }


    @Override
    public void deleteBySopId(String sopId) {
        List<BrGroupSopRule> ruleList = list(new LambdaQueryWrapper<BrGroupSopRule>().eq(BrGroupSopRule::getSopId, sopId)).stream().collect(Collectors.toList());
        if (ListUtils.isEmpty(ruleList)){
            return;
        }
        List<String> ruleIdList = ruleList.stream().map(e -> e.getId()).collect(Collectors.toList());
        batchDelete(new BatchDTO<String>().setIds(ruleIdList));
    }


    @Override
    public void batchDelete(BatchDTO<String> dto){

        //校验参数
        List<BrGroupSopRule> ruleList = new ArrayList<>();
        Optional.ofNullable(dto.getIds()).orElse(new ArrayList<>()).forEach(id -> ruleList.add(checkExists(id)));

        //删除
        removeByIds(dto.getIds());

        //删除detail关联
        detailService.remove(new LambdaQueryWrapper<BrGroupSopDetail>().in(BrGroupSopDetail::getRuleId, dto.getIds()));

        //删除待办
        todoService.remove(new LambdaQueryWrapper<BrTodo>().in(BrTodo::getBusinessId, dto.getIds()).eq(BrTodo::getType, BrTodo.GROUP_SOP_TYPE));

        //删除定时任务
        List<Integer> jobIds = new ArrayList<>();
        ruleList.stream().forEach(rule -> {
            if (ListUtils.isNotEmpty(rule.getJobId())) {
                jobIds.addAll(rule.getJobId());
            }
        });
        if (ListUtils.isNotEmpty(jobIds)) {
            jobIds.forEach(jobId -> {
                xxlJobService.delete(jobId);
            });
        }

    }


    /**
     * 翻译
     * @param brGroupSopRule 实体
     * @return BrGroupSopRuleVO 结果集
     * @author ouyang
     * @date 2022-04-17
     */
    private BrGroupSopRuleVO translation(BrGroupSopRule brGroupSopRule){
        BrGroupSopRuleVO vo = new BrGroupSopRuleVO();
        BeanUtils.copyProperties(brGroupSopRule, vo);
        return vo;
    }


    @Override
    public BrGroupSopRule checkExists(String id){
        if (StringUtils.isBlank(id)) {
            return null;
        }
        BrGroupSopRule byId = getById(id);
        if (byId == null) {
            throw new BaseException("群sop规则不存在");
        }
        return byId;
    }
}
